import React, {PureComponent} from "react";
import {
    Platform,
    StyleSheet,
    Text,
    View,
    Button,
    ScrollView,
    Image,
    Dimensions,
    TouchableOpacity,
    NativeModules,
} from "react-native";
import MineCourseDetailHeaderView from "../../widget/course/MineCourseDetailHeaderView";
import RefreshListView, {RefreshState} from "react-native-refresh-list-view";
import MineCourseDetailCell from "../../widget/course/MineCourseDetailCell";
import method from "../../api/method";
import api from "../../api/api";
import NetTool from "../../api/NetTool";
import Tips from "react-native-root-tips";
import ZiLiaoScene from "./ZiLiaoScene";
import CommonCofirmAlertDialog from "../../widget/dialog/CommonCofirmAlertDialog";

const {
    width
} = Dimensions.get('window')


type Props = {
    navigation: any,
}

type State = {
    data: Array < Object >,
    refreshState: number,
}
export default class MineCourseDetailScene extends PureComponent < Props, State > {
    static navigationOptions = ({
        navigation
    }: any) => ({
        headerTintColor: 'black',
        title: '课程详情',
        headerLeft: <TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>,
        headerRight: <TouchableOpacity
            onPress={()=>{navigation.navigate('ZiLiaoScene',{info:navigation.state.params.info})}}
            style={{borderRadius:10,marginRight:12,backgroundColor:'#db3843',width:54,height:20,justifyContent:'center',alignItems:'center'}}>
            <Text style={{fontSize:13,color:'#FFFFFF'}}>资料</Text>
        </TouchableOpacity>
    })

    constructor(props) {
        super(props)
        this.state = {
            data: [],
            refreshState: RefreshState.Idle,
            mine_detail: {
                start_date: '',
                end_date: '',
            },
            show: false,
            title: '',
            subtitle: '',
        }
    }

    componentDidMount() {

        this.requestFirstPage()
    }

    requestData = async() => {
        const {
            info
        } = this.props.navigation.state.params
        let params = {
            courseId: info.id,
        }
        let json = await NetTool.fetchGetRequest(api.getUserCourse, method.get, params)

        this.setState({
            mine_detail: json
        })

        let dataList = json.lessons.map((info) => {
            return {
                id: info.id,
                title: info.title,
                year: info.start_time.substr(5, 6),
                start_time: info.start_time,
                end_time: info.end_time,
                live_status: info.redirect_url ? '回放' : '未开始',
                live_url: info.is_living ? info.living_url : info.redirect_url,
                backUrl: info.backUrl,
            }
        })


        if (json.code) {
            Tips.showWarn(json.Message, {
                mask: true
            })
        }

        return dataList
    }

    requestFirstPage = async() => {

        try {
            this.setState({
                refreshState: RefreshState.HeaderRefreshing
            })
            let dataList = await this.requestData()

            this.setState({
                data: dataList,
                refreshState: RefreshState.Idle,
            })
        } catch (error) {
            this.setState({
                refreshState: RefreshState.Failure,
            })
        }
    }

    requestNextPage = () => {

    }

    //custon ui
    keyExtractor = (item: Object, index: number) => {
        return index + ''
    }

    _onpress(item) {
        let zhibo_time = new Date(item.item.start_time.replace(/-/g, "/")).getTime()
        let end_time = new Date(item.item.end_time.replace(/-/g, "/")).getTime()

        let current_time = new Date().getTime()

        if ((zhibo_time - current_time) < 30 * 60 && (zhibo_time - current_time) > 0) {
            this.setState({show: true, title: 'APP暂未开放直播功能', subtitle: '请去www.jkzaixian.com进行观看直播'})

        } else if (current_time > zhibo_time && current_time < end_time) {
            this.setState({show: true, title: 'APP暂未开放直播功能', subtitle: '请去www.jkzaixian.com进行观看直播'})

        } else if (current_time > end_time) {
            // const navigationAction = NavigationActions.navigate({
            //     routeName: 'videoScene',
            //     params: {},
            // })

            if (Platform.OS === 'ios') {
                this.props.navigation.navigate('videoScene', {url: item.item.backUrl, title: item.item.title})
            } else if (Platform.OS === 'android') {
                // alert('桥接！')
                NativeModules.MyVideoModule.callPlayMethod(item.item.backUrl, item.item.title);
            }

        }

    }

    renderCell = (item: any) => {
        return <MineCourseDetailCell info={item.item} navigation={this.props.navigation}
                                     onPress={()=>{this._onpress(item)}}/>
    }
    _headerComponent = () => {
        return <MineCourseDetailHeaderView detail={this.state.mine_detail}/>
    }

    _temSeparatorComponent() {
        return <View style={{width:width,height:20,backgroundColor:'white'}}/>
    }

    render() {
        return (
            <View style={{flex:1,backgroundColor:'white'}}>
                <RefreshListView
                    data={this.state.data}
                    ListHeaderComponent={this._headerComponent}
                    renderItem={this.renderCell}
                    keyExtractor={this.keyExtractor}
                    refreshState={this.state.refreshState}
                    onHeaderRefresh={this.requestFirstPage}
                    onFooterRefresh={this.requestNextPage}
                    ItemSeparatorComponent={()=>this._temSeparatorComponent()}
                />
                <CommonCofirmAlertDialog title={this.state.title} subtitle={this.state.subtitle} closeModal={
                    (st)=>{this.setState({show:st})}
                } show={this.state.show}/>
            </View>
        )
    }
}